package handler.impl;/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2020-01-10 11:45
 * @notify
 * @version 1.0
 */

import handler.ParameterHandler;
import handler.ResultSetHandler;
import handler.StatementHandler;
import mapping.BoundSql;
import mapping.Configuration;
import mapping.MappedStatement;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

public class PreparedStatementHandler<E> implements StatementHandler {

    @Override
    public Statement prepare(Connection connection, String sql) throws Exception {
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        return preparedStatement;
    }

    @Override
    public void setParam(Configuration configuration, Statement statement, MappedStatement mappedStatement, Object param) throws Exception {
        ParameterHandler parameterHandler = configuration.newParameterHandler();
        parameterHandler.handleParameter(statement, mappedStatement, param);
    }

    @Override
    public E query(Configuration configuration, MappedStatement mappedStatement, Statement statement) throws Exception {
        PreparedStatement preparedStatement = (PreparedStatement) statement;
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetHandler resultSetHandler = configuration.newResultSetHandler();
        return (E) resultSetHandler.handleResultSet(mappedStatement, resultSet);
    }

    @Override
    public boolean insert(Statement statement) throws Exception {
        PreparedStatement preparedStatement = (PreparedStatement) statement;
        return preparedStatement.execute();
    }
}
